/***************************************************************************
创建者：华磊
 开始时间：               : 2020.1１.01
 copyright            : (C) 深圳市华友高科有限公司
 修改说明：（每次有修改就添加一条，带有 修改人，修改时间，修改描述）

 ***************************************************************************
 *   程序运行视窗
*                                                                         *
 ***************************************************************************/
#include "runview.h"
#include "ui_runview.h"
#include <QtCore>
#include <QSize>
#include <QScrollBar>
#include <QTableWidget>
#include <QMessageBox>


//初始化成员变量
RunView::RunView(int styleId,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RunView)
{
     ui->setupUi(this);

     currentSelectRow = 1;//默认程序第一行

     currentSelectTab = 0;//默认卡片一

     strList << tr("指令及注释");//表头

     model = new QStringListModel;

     tmpFileSize = 0;
     for(int i =0;i< RUNVIEW_TABLE_SIZE ;i++)        //目前先初始化10个(表格\文件名缓存\行号缓存)
     {
         newTableWidget = new QTableWidget;
         newTableWidget->verticalScrollBar()->setStyleSheet("QScrollBar{width: 25px;}"
                                  "QScrollBar::handle{width: 25px;background:lightgray; border-radius:20px;}"
                                  "QScrollBar::handle:hover{width: 25px;background:green;}"
                                  "QScrollBar::sub-line{background:transparent;}"
                                  "QScrollBar::add-line{background:transparent;}");

         newTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑

         connect(newTableWidget,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(newTableWidget_doubleClicked(QModelIndex)));
         connect(newTableWidget,SIGNAL(clicked(QModelIndex)),this,SLOT(newTableWidget_clicked(QModelIndex)));

         //设置头部
         newTableWidget->setHorizontalHeaderLabels(strList);

         vectorTableWidget.append(newTableWidget);
         vectorTableWidget[i]->setColumnCount(1);
         vectorTableWidget[i]->setColumnWidth(0, 400);
         lastRunningLineId.append(0);
         switch (styleId) {
         case 1:
             vectorTableWidget[i]->setColumnWidth(0, 515);
             break;
         default:
             break;
         }

         //预先开辟 10 (RUNVIEW_TABLE_SIZE) 个 : 空文件名 ; 空行号 ;空指令
         tmpRunProInfo.runingFileName.append("");
         tmpRunProInfo.runingFileLine.append(0);
         //QStringList list;
         //tmpRunProInfo.runingFileCode.append(list);
     }
     newTableWidget->clear();

     setGeometry(75,130,460,595);

     initialDisplayStyle(styleId);

     runFileUpdateFlag = true;

     tmpPicAddress = "";

     currentProductivity = 1;
     accumulateProductivity = 1;
     runEfficiency = 1;

     robotPicture = "";
//     ui->PunchImageBtn->setStyleSheet( QString("border-image: url(%1);").arg(robotPicture) );//此行为占资源

//     ui->takeOFButton_fetch->setText(tr("强制取料"));
//     ui->takeOFButton_putdown->setText(tr("强制放料"));
//     ui->pushbt_clearCurrent->setText(tr("清除"));
//     ui->pushbt_clearAll->setText(tr("清除"));

//     ui->PunchImageBtn->setEnabled(false);

     //设置行的弹框页面
     setLineDialog = new SetLineDialog;
     setLineDialog->hide();
}

RunView::~RunView()
{

}

void RunView::initialDisplayStyle(int styleId)
{
    switch (styleId) {
    case 1:
        ui->widgetRunMode->setGeometry(5,90-60,580,380+80);
        ui->line->setGeometry(0,5,600,2);
        ui->line_2->setGeometry(0,150,600,2);
        ui->fileNameListView->setGeometry(5,40,600-5-150-30,105);
        ui->PunchImageBtn->setGeometry(600-150-20,10,150,135);
        ui->runFileTabWidget->setGeometry(5,155,600-30,195+60);
        break;
    default:
        break;
    }
}
//void RunView::on_takeOFButton_fetch_clicked()
//{
//    emit forceFetchMaterialSignal();
//}

//void RunView::on_takeOFButton_putdown_clicked()
//{
//    emit forcePutDownMaterialSignal();
//}

void RunView::on_pushbt_clearCurrent_clicked()
{
    QMessageBox message(QMessageBox::Question, "提示", "是否归零当前产量寄存器R[1]?"
                        , QMessageBox::Yes|QMessageBox::No , NULL);
    if(message.exec() == QMessageBox::No)
    {
        return;
    }
    emit clearCurrentProductivitySignal();
}

//void RunView::on_pushbt_clearAll_clicked()
//{
//    emit clearAccumulateProductivitySignal();
//}

void RunView::updateViewShow()
{
    ui->CurOutputShowLabel->setText(QString::number(currentProductivity));

    ui->accumOutputShowLabel->setText(QString::number(accumulateProductivity));

    ui->OperEfficeShowLabel->setText(QString::number(runEfficiency,'f',2));

    //初始化新增文件的table控件
    //qDebug()<<"tmpPicAddress"<<tmpPicAddress;
    //qDebug()<<"-------"<<robotPicture;
    if(runFileUpdateFlag)
    {

        //更新tab内容
        int sizeSum = runProInfo.runingFileName.size();
        //qDebug()<< "sizeSum ::" << sizeSum;
        //qDebug()<< "tmpFileSize ::" << tmpFileSize;
        //由于目前容器只有10个,限制循环数量防止越位
        if(sizeSum > RUNVIEW_TABLE_SIZE){sizeSum = RUNVIEW_TABLE_SIZE;}

        if(sizeSum != tmpFileSize)
        {
            //currentSelectTab = 0;//标签回归0

            tmpFileSize = sizeSum;//缓存状态:文件数量

            ui->runFileTabWidget->clear();
            for(int i = 0; i < sizeSum; i++)
            {
                int codeSize = runProInfo.runingFileCode[i].size();

                ui->runFileTabWidget->insertTab(i,vectorTableWidget[i],runProInfo.runingFileName[i]);

                // 设置Table控件行数
                vectorTableWidget[i]->setRowCount( codeSize );

                //头部
                vectorTableWidget[i]->setHorizontalHeaderLabels(strList);

                //设置内容
                QTableWidgetItem *tmpLineItem;
                for(int j = 0; j < codeSize; j++)
                {
                    tmpLineItem=new QTableWidgetItem( runProInfo.runingFileCode[i][j]);
                    tmpLineItem->setBackground(QBrush(QColor(255, 255, 255)));
                    vectorTableWidget[i]->setItem(j, 0, tmpLineItem );
                    qDebug() << "RunView::updateViewShot ==== Row:" << i << " InstructionStr =" << runProInfo.runingFileCode[i][j];
                }
                vectorTableWidget[i]->resizeRowsToContents();  //行高根据内容自适应
                showRunningLine(i,runProInfo.runingFileLine[i]);

                tmpRunProInfo.runingFileName[i] = runProInfo.runingFileName[i];//缓存状态:文件名
                tmpRunProInfo.runingFileLine[i] = runProInfo.runingFileLine[i];//缓存状态:行
            }
        }
        else                                //如果长度一致,只刷内容
        {
            for(int i = 0; i < sizeSum; i++)
            {
                //重新  设置内容
                if(runProInfo.runingFileName[i] != tmpRunProInfo.runingFileName[i])
                {
                    int codeSize = runProInfo.runingFileCode[i].size();

                    //设置tab标题
                    ui->runFileTabWidget->setTabText(i,runProInfo.runingFileName[i]);

                    //更新table控件的文字
                    vectorTableWidget[i]->setRowCount( codeSize );

                    //设置头部
                    vectorTableWidget[i]->setHorizontalHeaderLabels(strList);
                    //设置内容
                    QTableWidgetItem *tmpLineItem;
                    for(int j = 0; j < codeSize; j++)
                    {
                        tmpLineItem=new QTableWidgetItem( runProInfo.runingFileCode[i][j]);
                        tmpLineItem->setBackground(QBrush(QColor(255, 255, 255)));
                        vectorTableWidget[i]->setItem(j, 0, tmpLineItem );
                    }

                    vectorTableWidget[i]->resizeRowsToContents();  //行高根据内容自适应
                    tmpRunProInfo.runingFileName[i] = runProInfo.runingFileName[i];//缓存状态:文件名
                }

                //重新  设置高亮行
                if(i == currentSelectTab)//当前选中的tab 才刷,其他不刷
                {
                    if(runProInfo.runingFileLine[i] != tmpRunProInfo.runingFileLine[i])
                    {
                        showRunningLine(i,runProInfo.runingFileLine[i]);
                        tmpRunProInfo.runingFileLine[i] = runProInfo.runingFileLine[i];//缓存状态:行
                    }
                }
            }
        }

        //关联文件
        QStringList strListView;
        for(int i = 0; i < runProInfo.runRelatedFileName.size(); i ++)
        {
            strListView << runProInfo.runRelatedFileName[i];
        }

        model->setStringList(strListView);
        ui->fileNameListView->setModel(model);

        runFileUpdateFlag = false;
    }
}

void RunView::newTableWidget_clicked(const QModelIndex &index)
{
    //qDebug()<<"vectorTableWidget[0]->currentRow() = "<<index.row();//文件 程序下标
    //qDebug()<<"vectorTableWidget[0]->currentRow() = "<<index.row()+1;//行号

    currentSelectRow = index.row();
    emit setCurrentSelectRow();
}

void RunView::newTableWidget_doubleClicked(const QModelIndex &index)
{
    //qDebug()<<"vectorTableWidget[0]->currentRow() = "<<index.row();//文件 程序下标
    //qDebug()<<"vectorTableWidget[0]->currentRow() = "<<index.row()+1;//行号

    setLineDialog->show();
    currentSelectRow = index.row();
    setLineDialog->setLineText(currentSelectRow);
}

void RunView::changeLanguage(int language)
{
    if(1 == language)
    {
        translator.load("/agvwork/AgvHmi/baseBag/hmiProject/language/runViewEnglishLan.qm");
        qApp->installTranslator(&translator);
    }
    else
    {
        qApp->removeTranslator(&translator);
    }
    ui->retranslateUi(this);
    setLineDialog->changeLanguage();
}

void RunView::updateRobotPictureShow(std::string imageStringIn)
{
    QPixmap imgOut=stringTopixmap( QString::fromStdString(imageStringIn) );
    QPixmap imgScaled=imgOut.scaled(ui->PunchImageBtn->size(), Qt::KeepAspectRatio);
    ui->PunchImageBtn->setIcon(imgScaled);

}

QPixmap RunView::stringTopixmap(const QString &pic)
{
    QByteArray byte_array = QByteArray::fromBase64(pic.toLocal8Bit());
    QPixmap pix;
    QDataStream data_stream(&byte_array,QIODevice::ReadOnly);
    data_stream>>pix;
    return pix;
}

void RunView::showRunningLine(int tableIndex, int lineIndex)
{
    if(0>tableIndex || tableIndex>=vectorTableWidget.size())
    {
        return ;
    }
    //设置高亮行
    //  vectorTableWidget[i]->selectRow(runProInfo.runingFileLine[i]);
    QTableWidgetItem * tmpItem=vectorTableWidget[tableIndex]->item(lineIndex,0);
    if(nullptr==tmpItem)
    {
        return ;
    }
    QTableWidgetItem * tmpBeforeItem=vectorTableWidget[tableIndex]->item(lastRunningLineId[tableIndex],0);
    if(nullptr!=tmpBeforeItem)
    {
        tmpBeforeItem->setBackground(QBrush(QColor(255, 255, 255)));
    }
    vectorTableWidget[tableIndex]->scrollToItem(tmpItem,QAbstractItemView::PositionAtCenter);
    tmpItem->setBackground(QBrush(QColor(0, 255, 0)));
    lastRunningLineId[tableIndex]=lineIndex;

}

void RunView::on_runFileTabWidget_currentChanged(int index)
{
    //qDebug()<<"tab : "<<index;
    currentSelectTab = index;
}
